#include "ds/path_stack.h"
#include "utils.h"
// 新建一个空栈
Stack *stack_create()
{
    // callock可以不用手动初始化空指针
    return calloc(1, sizeof(Stack));
}
// 对于链式栈而言，销毁栈就是销毁链表
void stack_destroy(Stack *s)
{
    // 相当于遍历链表(出栈)然后在遍历中逐个free结点
    StackFrame *curr = s->top;
    while (curr != NULL)
    {
        StackFrame *tmp = curr->next; // 保存后继结点
        free(curr);
        curr = tmp;
    }
    // 最后free栈结构体
    free(s);
}

bool is_empty(Stack *s)
{
    return s->top == NULL;
}

// 相当于链表头插法插入结点，栈顶指针相当于链表的头指针
void stack_push(Stack *s, ElementType data)
{
    // 1.新建一个栈帧结点
    StackFrame *new_frame = malloc(sizeof(StackFrame));
    if (new_frame == NULL)
    {
        printf("malloc failed in stack_push.\n");
        exit(1);
    }
    // 2.初始化新栈帧
    new_frame->data = data;
    new_frame->next = s->top;
    // 3.更新栈顶指针
    s->top = new_frame;
}

// 相当于链表在头部删除第一个结点,栈顶指针相当于链表的头指针
ElementType stack_pop(Stack *s)
{
    // 1.栈判空处理
    if (is_empty(s))
    {
        printf("error: stack is empty.\n");
        return NULL;
    }
    // 2.出栈返回栈顶元素,并free结点,更新栈顶指针
    StackFrame *curr = s->top;
    ElementType data = curr->data;
    s->top = curr->next;
    free(curr);
    return data;
}
ElementType stack_peek(Stack *s)
{
    if (is_empty(s))
    {
        printf("error: stack is empty.\n");
        exit(1);
    }
    return s->top->data;
}
